package com.dlc.shop.groupbuy.common.listener;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.enums.ProdType;
import com.dlc.shop.bean.event.EsProductActivityInfoEvent;
import com.dlc.shop.bean.order.EsProductOrder;
import com.dlc.shop.bean.vo.search.GroupActivitySearchVO;
import com.dlc.shop.bean.vo.search.ProductSearchVO;
import com.dlc.shop.common.util.BeanUtil;
import com.dlc.shop.groupbuy.common.dao.GroupActivityMapper;
import com.dlc.shop.groupbuy.common.model.GroupActivity;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 获取商品团购数据事件
 * @author yami
 */
@Component("groupBuyEsProductActivityInfoListener")
@AllArgsConstructor
public class EsProductActivityInfoListener {

    private final GroupActivityMapper groupActivityMapper;


    @EventListener(EsProductActivityInfoEvent.class)
    @Order(EsProductOrder.GROUP_BUY)
    public void groupBuyEsProductListener(EsProductActivityInfoEvent event) {
        Long currentTime = System.currentTimeMillis();
        List<ProductSearchVO> productList = event.getProductList();
        List<Long> activityIds = productList.stream()
                .filter(productSearchVO -> Objects.equals(productSearchVO.getProdType(), ProdType.PROD_TYPE_GROUP.value())
                )
                .map(ProductSearchVO::getActivityId)
                .collect(Collectors.toList());
        // 没有开始中的团购商品需要处理
        if (CollUtil.isEmpty(activityIds)) {
            return;
        }
        List<GroupActivity> groupActivities = groupActivityMapper.selectList(new LambdaQueryWrapper<GroupActivity>().in(GroupActivity::getGroupActivityId, activityIds));
        Map<Long, GroupActivity> groupMap = groupActivities.stream().collect(Collectors.toMap(GroupActivity::getGroupActivityId, g -> g));
        for (ProductSearchVO productSearchVO : productList) {
            GroupActivity groupActivity = groupMap.get(productSearchVO.getActivityId());
            if (Objects.isNull(groupActivity)){
                continue;
            }
            productSearchVO.setActivityStatus(groupActivity.getStatus());
            productSearchVO.setGroupNumber(groupActivity.getGroupNumber());
            if (Objects.isNull(productSearchVO.getActivityStartTime()) || (productSearchVO.getActivityStartTime() > currentTime)){
                continue;
            }
            GroupActivitySearchVO groupActivitySearchVO = BeanUtil.map(groupActivity, GroupActivitySearchVO.class);
            productSearchVO.setActivityInProgress(Boolean.TRUE);
            productSearchVO.setGroupActivitySearchVO(groupActivitySearchVO);
        }
    }

}
